package com.yotoodesign.dianba.fragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicInteger;

import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.yotoodesign.dianba.R;
import com.yotoodesign.dianba.adapter.TopAdapter;
import com.yotoodesign.dianba.adapter.TopSingerAdapter;
import com.yotoodesign.dianba.adapter.TopSongAdapter;
import com.yotoodesign.dianba.app.GlobalApplication;
import com.yotoodesign.dianba.bean.BaseData;
import com.yotoodesign.dianba.bean.Singer;
import com.yotoodesign.dianba.bean.Song;
import com.yotoodesign.dianba.ui.MainActivity;
import com.yotoodesign.dianba.ui.ShakeActivity;
import com.yotoodesign.dianba.util.Constant;
import com.yotoodesign.dianba.util.DataUtils;
import com.yotoodesign.dianba.util.GuidePageChangeListener;
import com.yotoodesign.dianba.util.SingerService;
import com.yotoodesign.dianba.util.SongService;


public class HomeFragment extends BaseFragment{

	FragmentTransaction ft;
	SingerFragment singerFragment;
	
	private ViewPager topPager = null;
	private ImageView[] imgFocuses = null;
	private ImageView imageView = null;
	private AtomicInteger what = new AtomicInteger(0);
	private boolean isContinue = true;
	
	private Thread thread = null;
	
	private PopupWindow popArea;
	/*
	 * 当前位置
	 */
	private Address currentAddress;
	
	private ArrayList<BaseData> top10songs;
	
	private SingerSongFragment singerSongFragment;
	
	private Handler viewHandler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			topPager.setCurrentItem(msg.what);
			super.handleMessage(msg);
		}
		
	};
	
	public HomeFragment(){
		
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		return inflater.inflate(R.layout.home_fragment, container,false);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		
		initViewPager();
		
		//设置按钮事件
		int[] buttons = {R.id.btnHuaMan,R.id.btnHuaWoman,R.id.btnGangMan,R.id.btnGangWoman,
					R.id.btnHua,R.id.btnYue,R.id.btnEnglish,R.id.btnJapan,
					R.id.btnPinyin,R.id.btnQingge};
		for(int i = 0;i<buttons.length;i++){
			ImageButton button = (ImageButton)getView().findViewById(buttons[i]);
			button.setOnClickListener(addClickListener());
		}
	}
	
	private View.OnClickListener addClickListener(){
		return new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				switch (v.getId()){
				case R.id.btnHuaMan:
					SingerService.getInstance().initData(Singer.HUA, Singer.MALE);
					addSingerFragment(Constant.TAG_SINGER,DataUtils.loadSingers());
					break;
				case R.id.btnHuaWoman:
					SingerService.getInstance().initData(Singer.HUA, Singer.FEMALE);
					addSingerFragment(Constant.TAG_SINGER,DataUtils.loadSingers());
					break;
				case R.id.btnGangMan:
					SingerService.getInstance().initData(Singer.GANG, Singer.MALE);
					addSingerFragment(Constant.TAG_SINGER,DataUtils.loadSingers());
					break;
				case R.id.btnGangWoman:
					SingerService.getInstance().initData(Singer.GANG, Singer.FEMALE);
					addSingerFragment(Constant.TAG_SINGER,DataUtils.loadSingers());
					break;
					
					
				case R.id.btnHua:
					SongService.getInstance().initData(Song.HUA);
					addSingerSongFragment(Constant.TAG_SINGER_SONG,
							new Singer(getString(R.string.hua_man),getString(R.string.hua_man)), 
							SongService.getInstance().first(),false);
					break;
				case R.id.btnYue:
					SongService.getInstance().initData(Song.YUE);
					addSingerSongFragment(Constant.TAG_SINGER_SONG,
							new Singer(getString(R.string.yue_type),getString(R.string.yue_type)), 
							SongService.getInstance().first(),false);
					break;
				case R.id.btnEnglish:
					SongService.getInstance().initData(Song.ENGLISH);
					addSingerSongFragment(Constant.TAG_SINGER_SONG,
							new Singer(getString(R.string.english_type),getString(R.string.english_type)), 
							SongService.getInstance().first(),false);
					break;
				case R.id.btnJapan:
					SongService.getInstance().initData(Song.JAPAN);
					addSingerSongFragment(Constant.TAG_SINGER_SONG,
							new Singer(getString(R.string.japan_type),getString(R.string.japan_type)),
							SongService.getInstance().first(),false);
//					Share2Friends dialog = DialogUtil.showSharedDialog(getActivity(),
//							"分享到朋友圈", GlobalApplication.getMainActivity().getTabHost(), Gravity.TOP);
//					dialog.setOnOkClickListener(new Share2Friends.OkClickListener() {
//						
//						@Override
//						public void onClick(View v) {
//							
//						}
//					});
					break;
				case R.id.btnPinyin:
					SongService.getInstance().initData(Song.PINYIN);
					addSingerSongFragment(Constant.TAG_SINGER_SONG,
							new Singer(getString(R.string.pinyin_type),getString(R.string.pinyin_type)),
							SongService.getInstance().first(),false);
					break;
				case R.id.btnQingge:
//					SongService.getInstance().initData(Song.TWO_SINGER);
//					addSingerSongFragment(Constant.TAG_SINGER_SONG,
//							new Singer(getString(R.string.qingge_type),getString(R.string.qingge_type)),
//							SongService.getInstance().first(),false);
					Intent intent = new Intent();
					intent.setClass(getActivity(), ShakeActivity.class);
					startActivity(intent);
					break;
				}
			}
		};
	}
	
	//添加SingerFragment
	private void addSingerFragment(String tabId,ArrayList<BaseData> singerList){
		
		FragmentManager fm = getActivity().getSupportFragmentManager();
		ft = fm.beginTransaction();
		ft.setCustomAnimations(R.anim.zoomin_fragment,R.anim.zoomout_fragment);
		//先detach主Fragment
		ft.hide(this);
		singerFragment = (SingerFragment)fm.findFragmentByTag(tabId);
		if(singerFragment==null){
			try {
				singerFragment = new SingerFragment();
				ft.add(R.id.realtabcontent,singerFragment, tabId);
				//添加到后退堆栈里
				ft.addToBackStack(tabId);
			} catch (Exception e) {
				e.printStackTrace();
			}						
		}else{
			ft.attach(singerFragment);						
		}
		
		singerFragment.setTitle("歌星点歌");
		singerFragment.setDataList(singerList);
		
		ft.commit();
	}

	@Override
	public void updateListView() {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onResume() {
		super.onResume();
		MainActivity mainActivity = (MainActivity)this.getActivity();
	}
	
	/*
	 * 初始化Top10
	 */
	private void initViewPager() {
		topPager = (ViewPager)getView().findViewById(R.id.top_pager);
		ViewGroup group = (ViewGroup)getView().findViewById(R.id.viewGroup);
		
		List<View> top10s = new ArrayList<View>();
		//add view
		View top10song = loadTop10Songs();
		top10s.add(top10song);
		
		View top10singer = loadTop10Singers();
		top10s.add(top10singer);
		
		imgFocuses = new ImageView[top10s.size()];
		for(int i = 0;i<top10s.size();i++){
			imageView = new ImageView(getActivity());
			imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
			imageView.setPadding(5,0,5,0);
			imgFocuses[i] = imageView;
			if(i == 0){
				imgFocuses[i].setBackgroundResource(R.drawable.banner_dian_focus);
			}else{
				imgFocuses[i].setBackgroundResource(R.drawable.banner_dian_blur);
			}
			group.addView(imgFocuses[i]);
		}
		
		topPager.setAdapter(new TopAdapter(top10s));
		topPager.setOnPageChangeListener(new GuidePageChangeListener(imgFocuses,what));
		topPager.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				case MotionEvent.ACTION_DOWN:
				case MotionEvent.ACTION_MOVE:
					isContinue = false;
					break;
				case MotionEvent.ACTION_UP:
					isContinue = true;
					break;
				default:
					isContinue = true;
					break;
				}
				return false;
			}
		});
		
		/** 启动线程循环显示排行榜
		isContinue = true;
		
		thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				while(true){
					if( isContinue){
						viewHandler.sendEmptyMessage(what.get());
						whatHandler();
					}
				}
				
			}
		});
		
		thread.start();
		**/
	}
	
	
	@Override
	public void onDestroyView() {
		isContinue = false;
//		thread.interrupt();
		super.onDestroyView();
	}

	private void whatHandler(){
		what.incrementAndGet();
		if(what.get()>imgFocuses.length-1){
			what.getAndAdd(-imgFocuses.length);
		}
		
		try {
			Thread.sleep(2*Constant.SECOND);
		} catch (InterruptedException e) {
		}
	}
	
	

	/*
	 * 加载Top10歌曲
	 */
	private View loadTop10Songs(){
		if(top10songs==null){
			top10songs = DataUtils.loadTop10Songs();
		}
		
		
		//新的顺序
		int[] seqs = {
				1,6,
				2,7,
				3,8,
				4,9,
				5,10};
		ArrayList<BaseData> songsSorted = new  ArrayList<BaseData>();
		for(int i = 0;i<seqs.length;i++){
			songsSorted.add(top10songs.get(seqs[i]-1));
		}
		
		View top10song = LayoutInflater.from(getActivity()).inflate(R.layout.top10_song, null);
		
		GridView songGrid = (GridView)top10song.findViewById(R.id.songGrid);
		final TopSongAdapter songAdapter = new TopSongAdapter(getActivity());
		songAdapter.setSongList(songsSorted);
		songGrid.setAdapter(songAdapter);
		songGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//显示歌曲详情
				showTopSongDetail((Song)songAdapter.getSongList().get(position));
			}
		});
		
		return top10song;
	}
	
	/*
	 * 加载Top10歌手
	 */
	private View loadTop10Singers(){
		ArrayList<BaseData> singers = DataUtils.loadTop10Singers();
		
		//新的顺序
		int[] seqs = {
				1,6,
				2,7,
				3,8,
				4,9,
				5,10};
		ArrayList<BaseData> songsSorted = new  ArrayList<BaseData>();
		for(int i = 0;i<seqs.length;i++){
			songsSorted.add(singers.get(seqs[i]-1));
		}
		
		View top10singer = LayoutInflater.from(getActivity()).inflate(R.layout.top10_singer, null);
		
		GridView singerGrid = (GridView)top10singer.findViewById(R.id.singerGrid);
		final TopSingerAdapter singerAdapter = new TopSingerAdapter(getActivity());
		singerAdapter.setSingerList(songsSorted);
		singerGrid.setAdapter(singerAdapter);
		singerGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				//显示歌曲详情
				Singer singer = (Singer)singerAdapter.getSingerList().get(position);
				addSingerSongFragment(Constant.TAG_SINGER_SONG,singer,
						DataUtils.loadSingerSongs(singer),true);
			}
		});
		
		return top10singer;
	}
	
	private View.OnClickListener showAreaHandler(){
		return new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				/*
				if(popArea == null){
					View area = LayoutInflater.from(getActivity()).inflate(R.layout.area_selector, null);
					popArea = new PopupWindow(area,LayoutParams.MATCH_PARENT,300,true);
					popArea.setOutsideTouchable(true);
					popArea.setFocusable(true);
					popArea.update();
					
					Button btnArea = (Button)getView().findViewById(R.id.btnArea);
					popArea.showAsDropDown(btnArea,0,0);
				}
				
				if(popArea.isShowing()){
					popArea.dismiss();
				}
				*/
				
			}
		};
	}
	

	
	/*
	 * 获取用户当前位置
	 * http://api.map.baidu.com/place/search?&query=KTV&location=31.52,117.17&radius=2000&output=xml&key=37492c0ee6f924cb5e934fa08c6b1676
	 */
	private void getUserLocation(){
		Toast.makeText(getActivity(), "正在定位当前位置...", Toast.LENGTH_SHORT).show();
		
		LocationManager locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
		Criteria criteria = new Criteria(); 
		// 获得最好的定位效果 
		criteria.setAccuracy(Criteria.ACCURACY_FINE); 
		criteria.setAltitudeRequired(false); 
		criteria.setBearingRequired(false); 
		criteria.setCostAllowed(false); 
		// 使用省电模式 
		criteria.setPowerRequirement(Criteria.POWER_LOW); 
		// 获得当前的位置提供者 
		String provider = locationManager.getBestProvider(criteria, true); 
		// 获得当前的位置 
		Location location = locationManager.getLastKnownLocation(provider); 
		// 获得当前位置的纬度 
		Double latitude = location.getLatitude() * 1E6; 
		// 获得当前位置的经度 
		Double longitude = location.getLongitude() * 1E6;
		
		String msg = "";
		Geocoder gc = new Geocoder(getActivity(),Locale.CHINA); 
		List<Address> addresses = new ArrayList<Address>();
		boolean successed = false;
		try {
			addresses = gc.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
			successed = true;
		} catch (IOException e) {
			Log.i(Constant.DIANBA,"getLocation error:"+e.getMessage());
			successed = false;
		} 
		if(successed){
			if (addresses.size() > 0) { 
				currentAddress = addresses.get(0);
				
				msg += "AddressLine：" + currentAddress.getAddressLine(0)+ "\n"; 
				msg += "CountryName：" + currentAddress.getCountryName()+ "\n"; 
				msg += "Locality：" + currentAddress.getLocality() + "\n"; 
				msg += "FeatureName：" + currentAddress.getFeatureName(); 
				Log.i(Constant.DIANBA,"location>>>"+msg);
			} 
			
		}
		
	}
	/*
	 * 显示歌曲详情
	 */
	private void showTopSongDetail(final Song song){
		final LinearLayout topDetail = (LinearLayout)getView().findViewById(R.id.topDetail);
		TextView tvSongName = (TextView)topDetail.findViewById(R.id.tvSongName);
		TextView tvSingerName = (TextView)topDetail.findViewById(R.id.tvSingerName);
		TextView tvSingerDesc = (TextView)topDetail.findViewById(R.id.tvSingerDesc);
		TextView tvCount = (TextView)topDetail.findViewById(R.id.tvCount);
		final Button btnAdd2List = (Button)topDetail.findViewById(R.id.btnAdd2List);
		Button btnBack2List = (Button)topDetail.findViewById(R.id.btnBack2List);
		
		final ViewPager top_pager = (ViewPager)getView().findViewById(R.id.top_pager);
		
		tvSongName.setText(song.getName());
		if(song.getSinger()!=null){
			tvSingerName.setText(song.getSinger().getName());
			tvSingerDesc.setText(song.getSinger().getDesc());
		}
		tvCount.setText(getString(R.string.vod_count)+song.getFavoritesCount());
		
		//切换样式
		toggleStyle(btnAdd2List,isSelected(song));
		
		btnAdd2List.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				toggleSelect(btnAdd2List,song);
			}
		});
		
		btnBack2List.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				top_pager.setVisibility(View.VISIBLE);
				topDetail.setVisibility(View.GONE);
				Animation animation = AnimationUtils.loadAnimation(getActivity(), 
		        		R.anim.push_song_detail_out);
				topDetail.startAnimation(animation);
			}
		});
		
		
		topDetail.setVisibility(View.VISIBLE) ;
		
		Animation animation = AnimationUtils.loadAnimation(getActivity(), 
        		R.anim.push_song_detail_in);
		topDetail.startAnimation(animation);
		animation.setAnimationListener(new AnimationListener() {
			@Override
			public void onAnimationStart(Animation animation) {
			}
			@Override
			public void onAnimationRepeat(Animation animation) {
			}
			@Override
			public void onAnimationEnd(Animation animation) {
				top_pager.setVisibility(View.GONE);
			}
		});
	}
	
	//添加SingerSongFragment
	private void addSingerSongFragment(String tabId,Singer singer,ArrayList<BaseData> songList,boolean showUser){
		FragmentManager fm = getActivity().getSupportFragmentManager();
		ft = fm.beginTransaction();
		//先detach主Fragment
		ft.hide(this);
		singerSongFragment = (SingerSongFragment)fm.findFragmentByTag(tabId);
		if(singerSongFragment==null){
			try {
				singerSongFragment = new SingerSongFragment();
				ft.add(R.id.realtabcontent,singerSongFragment, tabId);
				//添加到后退堆栈里
				ft.addToBackStack(tabId);
			} catch (Exception e) {
				Log.i(Constant.DIANBA,"add to back stack error");
			}						
		}else{
			ft.attach(singerSongFragment);						
		}
		singerSongFragment.setSinger(singer);
		singerSongFragment.setTitle(singer.getName());
		singerSongFragment.setDataList(songList);
		singerSongFragment.setShowUser(showUser);
		ft.commit();
		
		MainActivity mainActivity = (MainActivity)this.getActivity();
		mainActivity.setCurrentFragment(singerSongFragment);
	}
	
	private void toggleSelect(Button btnAddSong,Song song){
		MainActivity activity = (MainActivity)GlobalApplication.activity;
		if(song.isSelected()){
			song.setSelected(false);
			activity.removeSong(song);
			btnAddSong.setBackgroundResource(R.drawable.green_button);
			btnAddSong.setText(getResources().getString(R.string.add2list));
		}else{
			song.setSelected(true);
			int[] location = new int[2];
			btnAddSong.getLocationOnScreen(location);
			activity.addSong(song,location[0],location[1]);
			btnAddSong.setBackgroundResource(R.drawable.red_button);
			btnAddSong.setText(getResources().getString(R.string.remove_from_list));
		}
		
	}
	
	private void toggleStyle(Button btnAddSong,boolean selected){
		if(selected){
			btnAddSong.setBackgroundResource(R.drawable.red_button);
			btnAddSong.setText(getResources().getString(R.string.remove_from_list));
		}else{
			btnAddSong.setBackgroundResource(R.drawable.green_button);
			btnAddSong.setText(getResources().getString(R.string.add2list));
		}
	}
	
	private boolean isSelected(Song song){
		boolean result = false;
		MainActivity main = GlobalApplication.getMainActivity();
		
		for(Iterator<Song> it = main.getCurrentList().iterator();it.hasNext();){
			Song s = it.next();
			if (song.getName().equals(s.getName())
					&& song.getSinger().getName()
							.equals(s.getSinger().getName())) {
				result = true;
				break;
			}
		}
		return result;
	}
	
}
